// ignore_for_file: unnecessary_null_comparison

import 'dart:collection';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:verse_systems/commom/routers/navigator_utils.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/net/src/sparrow_dio_config.dart';
import 'package:verse_systems/pages/login/login_state.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/widgets/alert.dart';

class LoginControl extends GetxController {
  final LoginState state = LoginState();

  // 账户
  final TextEditingController account = TextEditingController();
  // 密码
  final TextEditingController password = TextEditingController();

  /*用户协议**/
  handleProtocol() {
    NavigatorUtils.handleProtocol();
  }

  /*隐私协议**/
  handlePrivacy() {
    NavigatorUtils.handlePrivacy();
  }


  hanldeUserLogin({ Function? showError }) async {
    Map<String, dynamic> map = HashMap();
    map['phone'] = account.text.trim();
    map['sms_code'] = password.text.trim();
    map['login_type'] = 1;
    if (Platform.isAndroid) {
         map['device_type'] = "1";
      } else {
         map['device_type'] = "2";
      }
    Request.postCallback(
      HttpUrls.loginUrl,
      data: map,
      needToken: false,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);

        if (result.status == 0) {
          debugPrint("登录信息----->${result.data}");
          final token = result.data["token"];
          SparrowDioConfig.setToken(token);
          final bool status =   await AccountUtil.setUserToken(token);
           if (status) {
               state.isLogin = true;  
            }
        } else {
          showError!();
          Loading.showError(result.msg);
        }
      },
      error: (err) {
        Loading.showError("login_err_try_again".tr);
        Loading.dismiss();
      },
    );
  }


  hanldeGoToHome() {
     NavigatorUtils.goToHome();
  }

  hanldeToFirstOpen() {
    Future.delayed(const Duration(milliseconds: 500), () async {
      bool? isFirstOpen = await AccountUtil.getAppIsFirstOpen();
      if (isFirstOpen) {
        hanldeShowPolicy();
      }
    });
  }

  hanldeShowPolicy() async {
    Alert.showPolicySheet(onAgreement: () {
      NavigatorUtils.handleProtocol();
    }, onPrivacy: () {
      NavigatorUtils.handlePrivacy();
    });
  }

  @override
  void onInit() {
    super.onInit();
    hanldeToFirstOpen();
  }

  @override
  void dispose() {
    account.dispose();
    password.dispose();
    super.dispose();
  }
}
